<?php
/**
 * Protoweb's base controller with base functionality
 */
include_once 'pwcontroller.php';

/**
 * The controller user model
 *
 * Public controller methods are friendly urls thanks to {@link http://codeigniter.com
 * Codeigniter}.
 *
 * @author Gonzalez Federico, Viera Leonel
 * @package Protoweb
 * @subpackage controller
 */
class Users extends PwController
{

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->login();
    }

    /**
     * Test if user is logged
     *
     * @param string $url_error url to redirect if the User don't pass the test
     * @return User if true, else redirects
     */
    public static function security($level='logged', $project_id=0, $url_error="")
    {
        $user = User::logged();

        if ($user) {
            return ($user);
        }
        else {
            if ( ! strlen($url_error)) {
                $url_error = base_url() . "users/login/";
            }
            redirect($url_error);
        }
    }

    /**
    * Generates a cookie in order to identify the user as logged
    */
    public function login()
    {
        $data['user'] = new User();
        delete_cookie('protoweb_logged');

        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            // try to login
            $data['user']->where('username', $this->input->post('username'));
            $data['user']->where('password', md5($this->input->post('password')));
            $data['user']->get();
  
            if ($data['user']->id > 0) { 
                // Where are logged!
                $cookie = array(
                    'name'   => 'logged',
                    'value'  => $data['user']->id,
                    'expire' => '0', // will maintain while browser instance are opened
                    'prefix' => 'protoweb_'
                );
              
                set_cookie($cookie);
                redirect(base_url().'users/dashboard/');
            }
            else { // login failed
                $data['error']          = 'Please, check your Username and Password';
                $data['user']->username = $this->input->post('username');
                $data['user']->password = '';
            }
        } // end try login

        $this->smartyview->render('user_login.html', $data);
    } // public function login()

    /**
    * Loads users sign up view
    */
    public function signup()
    {
        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            $data = $this->sign_up_save();
        }
        else {
            $data["user"] = new User();
        }

        $this->smartyview->render("user_signup.html", $data);
    } // end method signup()

    /**
     * Saves a new user in Protoweb's DB
     *
     * @return array if error, else redirects
     */
    private function sign_up_save() 
    {
        $data["user"]            = new User();
        $data["user"]->username  = $this->input->post("username");
        $data["user"]->password  = $this->input->post("password");
        $data["user"]->email     = $this->input->post("email");
        $data["user"]->lastname  = $this->input->post("lastname");
        $data["user"]->firstname = $this->input->post("firstname");
        $data["user"]->phone     = $this->input->post("phone");
        $data["user"]->address   = $this->input->post("address");
        $data["user"]->latlng    = $this->input->post("latlng");
  
        if ($data['user']->password == $this->input->post("re-password")) {
            if ($data["user"]->save()) {
                redirect(base_url()."users/login/");
            }
            else {
                $data["error"]          = $data["user"]->error->string;
                $data["user"]->password = "";
            }
        }
        else {
            $data["error"]          = "<p>You typed two different passwords</p>";
            $data["user"]->password = "";
        }

        return ($data);
    } // end Method sign_up_save()

    /**
      * Load users dashboard view
      */
    public function dashboard()
    {
        // Users Security
        $data['user'] = Users::security();

        // Get active and inactive projects
        $data['active_projects']   = array();
        $data['inactive_projects'] = array();

        foreach ($data['user']->project as $project) {
            if ($project->active) {
                array_push($data['active_projects'], $project);
            }
            else {
                array_push($data['inactive_projects'], $project);
            }
        } // foreach
        
        if (count($data['active_projects']) == 0) {
            $data['active_projects'] = 0;
        }
        if (count($data['inactive_projects']) == 0) {
            $data['inactive_projects'] = 0;
        }

        $this->smartyview->render('user_dashboard.html', $data);
    } // End of method dashboard()


    /**
     * Destroys cookie in order to logout an user
     */
    public function logout()
    {
        delete_cookie("protoweb_logged");
        redirect(base_url()."users/login/");
    }

    /**
     * Loads users profile view
     *
     * @param integer $id ID of the user that will be edited
     */
    public function edit($id=0) 
    {
        // Users Security
        $data["user"] = Users::security();
  
        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            $data = $this->edit_save();
        }
        $this->smartyview->render("user_edit.html", $data);
    }

    /**
     * Saves user profile modifications in Protoweb's DB
     */
    private function edit_save()
    {
        $data["user"]            = new User($this->input->post("id"));
        $data["user"]->username  = $this->input->post("username");
        $data["user"]->email     = $this->input->post("email");
        $data["user"]->lastname  = $this->input->post("lastname");
        $data["user"]->firstname = $this->input->post("firstname");
        $data["user"]->phone     = $this->input->post("phone");
        $data["user"]->address   = $this->input->post("address");
        $data["user"]->latlng    = $this->input->post("latlng");
  
        if ($this->input->post("password") == $this->input->post("re-password")) {
  
            if (md5($this->input->post("password")) != $data["user"]->password) {
                $old_pass               = $data["user"]->password;
                $data["user"]->password = $this->input->post("password");
            }
  
            if ($data["user"]->save()) {
                $data["message"] = "Your personal information was saved successfully!";
            }
            else {
                $data["error"]          = $data["user"]->error->string;
                $data["user"]->password = $old_pass;
            }
        }
        else {
            $data["error"] = "You typed two different passwords";
        }
        return ($data);
    } // end Method edit_save()

    /**
     * Deletes relationshop between logged user and a project
     *
     * @param integer $project_id ID of the project to leave
     */
    public function leave_project($project_id=0)
    {
        // Users Security
        $user    = Users::security();
        $project = new Project($project_id);

        if ($user->delete($project)) {
            redirect(base_url()."users/dashboard/");
        }
    }

    /**
     * Use with AJAX. A query that search users by username, lastname and firstname
     */
    public function get_ajax()
    {
        // Users Security
        $user     = Users::security();
        $excluded = $this->input->post("members");

        // the query requires to overwrite $user
        $user = new User();
        
        $user->group_start();
        $user->or_like("username",$this->input->post("q"));
        $user->or_like("firstname",$this->input->post("q"));
        $user->or_like("lastname",$this->input->post("q"));
        $user->group_end();
        $user->where_not_in("id",$excluded);

        $res = "";
        foreach($user->get()->all as $row) {
          $res .= $row->fullname() . "|" . $row->id . "\r\n";
        }
        die($res);
    } // end of method get_ajax() 

    /**
     * Deletes a user from Protoweb's DB
     *
     * @param integer $id ID of the user to delete
     */
    public function delete()
    {
        // Users Security
        $user = Users::security();

        /* TODO Seguridad porque llama con Ajax */
        if ($user->delete()) {
            redirect(base_url());
        }
        else {
            redirect(base_url()."users/edit/");
        }
    }

} // class Users

/* End of file users.php */
/* Location: ./application/controllers/users.php */
